<template>
    <div class="main">
        <div class="register-box">
            <h1 style="text-align: center; padding-left: 40px; margin-bottom: 20px;">用户注册</h1>
            <el-form :model="registerForm" status-icon :rules="registerRules" ref="registerForm" label-width="100px"
                class="demo-ruleForm">
                <el-form-item label="用户名" prop="username">
                    <el-input type="text" v-model="registerForm.username" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input type="password" v-model="registerForm.password" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                    <el-input type="password" v-model="registerForm.confirmPassword" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input type="email" v-model="registerForm.email" autocomplete="off"
                        style="width: 200px;"></el-input>
                    <span style="margin-left: 30px;"><el-button type="primary"
                            @click="sendCaptcode">发送验证码</el-button></span>
                </el-form-item>
                <el-form-item label="邮箱验证码" prop="emailCode">
                    <el-input type="text" v-model="registerForm.emailCode" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item style="text-align: center; margin-right: 20px;">
                    <el-button type="primary" @click="register('registerForm')">注册</el-button>
                    <el-button @click="goBack">返回登录</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script>
import axios from 'axios';
import { validateUsername, validateEmail } from '@/utils/validate'
export default {
    methods: {
        goBack() {
            this.$router.push({ name: 'login' });
        },
        verify(){
            return axios.post('/user/verify', {
                email: this.registerForm.email,
                captcha: this.registerForm.emailCode
            }).then(response => {
                const data = response.data;
                if (!data.success) {
                    throw new Error(data.message || '验证码无效');
                }else {
                    this.$message.success('验证码验证成功');
                }
            });
        },

        
        register(formName) {
            this.$refs[formName].validate((valid) => {
                if(valid){
                    this.verify().then(() =>{
                        axios.post('/user/register', this.registerForm).then(res => {
                            if (res.status === 200) {
                                this.$message.success('注册成功')
                                this.$router.push({ name: 'login' });
                            } else {
                                this.$message.error('注册失败，请稍后再试')
                            }
                        }).catch(() => {
                            this.$message.error('注册失败，请稍后再试');
                        })
                    })
                }
            });
        },
        validateConfirmPassword(rule , value, callback){
            if(value !== this.registerForm.password){
                callback(new Error('两次输入的密码不一致'))
            }else{
                callback()
            }
        },
        sendCaptcode() {
            this.$refs['registerForm'].validateField('email', (errorMessage) => {
                if (!errorMessage) {
                    // 如果邮箱验证通过，则发送请求以获取验证码
                    axios.post('/user/send', { email: this.registerForm.email })
                        .then(response => {
                            const data = response.data;
                            if (data.success) {
                                this.$message.success(data.message);
                            } else {
                                this.$message.error(data.message);
                            }
                        })
                        .catch(error => {
                            this.$message.error('验证码发送失败，请检查网络连接或邮箱地址');
                        });
                } else {
                    this.$message.error('请提供有效的邮箱地址');
                }
            });
        }

    },
    data() {
        return{
            registerForm: {
                username: '',
                password: '',
                confirmPassword: '',
                email: '',
                emailCode: ' '
            },
            registerRules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { validator: validateUsername, trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' }
                ],
                confirmPassword: [
                    { required: true, message: '请再次输入密码', trigger: 'blur' },
                    { validator: this.validateConfirmPassword, trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    { validator: validateEmail, trigger: 'blur' }
                ],
                emailCode: [
                    { required: true, message: '请输入邮箱验证码', trigger: 'blur' }
                ]
            }
        }
    },

}
</script>

<style>
.main {
    height: 100%;
    width: 100%;
    background: url("../../assets/login.jpeg") center top no-repeat;
    position: relative;
}

.register-box {
    width: 450px;
    position: absolute;
    background-color: #fff;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    padding-top: 30px;
    padding-right: 30px;
    border-radius: 20px;
}
</style>